package tech.wetech.admin3.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tech.wetech.admin3.sys.exception.AooUserException;
import tech.wetech.admin3.sys.model.DID;
import tech.wetech.admin3.sys.service.AooPhoneCodeService;
import tech.wetech.admin3.sys.service.DIDService;
import tech.wetech.admin3.sys.service.OssService;
import tech.wetech.admin3.util.CustomResponse;
import tech.wetech.admin3.util.HashUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/did")
public class DIDController {
  private OssService ossService;
  private DIDService didService;
  private HashUtil hashUtil;
  private AooPhoneCodeService phoneCodeService;

  public DIDController(
    OssService ossService,
    DIDService didService,
    HashUtil hashUtil,
    AooPhoneCodeService phoneCodeService
  ) {
    this.ossService = ossService;
    this.didService = didService;
    this.hashUtil = hashUtil;
    this.phoneCodeService = phoneCodeService;
  }

  @GetMapping("/conut")
  public Integer count() {
    return didService.count();
  }

  @PostMapping("/update-image")   // 上传did身份证图片
  public ResponseEntity<?> updateImage(
    @RequestParam("didNo") String didNo,
    @RequestParam("image") MultipartFile image
  ) {
    DID did = didService.findByDidNo(didNo);

    if (!image.isEmpty()) {
      String idCardUrl = ossService.uploadImage(image);
      did.setIdCardUrl(idCardUrl);

      DID didNew = didService.update(did);
      return ResponseEntity.ok(new CustomResponse.r1("提交成功", true, didNew));
    } else {
      return ResponseEntity.ok(new CustomResponse.r1("图片为空", false, null));
    }
  }

  @GetMapping("/getdid/{didNo}")
  public ResponseEntity<?> getDIDByNo(@PathVariable String didNo) {
    DID did = didService.findByDidNo(didNo);

    if (did == null) {
      return ResponseEntity.ok(new CustomResponse.r2("未查询到结果", 1000, null));
    } else {
      return ResponseEntity.ok(new CustomResponse.r2("查询已完成", 1000, did));
    }
  }

  @DeleteMapping("/admin/deletedid")
  public String deleteDID(
    @RequestParam("serial") String serial,
    @RequestParam("vericode") String vericode
  ) {
    boolean flag = phoneCodeService.admin_VerifyCode(vericode);
    if(!flag){
      throw new IllegalArgumentException("admin 验证码错误或已过期");
    }

    try {
      didService.deleteBySerial(serial);
      return "DID with serial " + serial + " deleted successfully";
    } catch (RuntimeException e) {
      return e.getMessage();
    }
  }

  @GetMapping("/get-dids")
  public ResponseEntity<?> getDids() {
    List data = didService.getAll();
    return ResponseEntity.ok(new CustomResponse.r2("以获取DID身份列表", 1000, data));
  }

  @GetMapping("/admin/get-dids")
  public ResponseEntity<?> admin_getDids(
    @RequestParam("vericode") String vericode
  ) {
    boolean flag = phoneCodeService.admin_VerifyCode(vericode);
    if(!flag){
      throw new IllegalArgumentException("admin 验证码错误或已过期");
    }

    List data = didService.getAll();
    return ResponseEntity.ok(new CustomResponse.r2("以获取DID身份列表", 1000, data));
  }

  @Transactional
  @PostMapping("/blockchaincheck")    // 查询是否已 上链存证
  public ResponseEntity<?> blockchainCheck(
    @RequestParam(value = "serial", required = false) String serial,
    @RequestParam(value = "modelFileOrImage", required = false) MultipartFile modelFileOrImage,
    @RequestParam("mobile") String mobile,
    @RequestParam("vericode") String vericode
  ) {

    boolean flag = phoneCodeService.verifyCode(mobile, vericode);
    if (!flag) {
      return ResponseEntity.ok(new CustomResponse.r1<>("验证码错误或已过期", false, null));
    }
    phoneCodeService.deleteCode(mobile);  //  操作后删除验证码，使失效

    // 当只有serial参数时的处理逻辑
    if (serial != null && modelFileOrImage == null) {
      // 进行serial参数相关处理
      DID did = didService.findBySerial(serial);
      System.out.println("did----" + did);
      if (did == null) {
        return ResponseEntity.ok(new CustomResponse.r1<>("角色不存在", true, null));
      }
      String txhash_saveAuth = did.getTxhash_saveAuth();
      String idCardUrl = did.getIdCardUrl();
      Map<String, Object> result = new HashMap<>();
      result.put("txhash_saveAuth", txhash_saveAuth);
      result.put("idCardUrl", idCardUrl);
      if (txhash_saveAuth != null) {
        return ResponseEntity.ok(new CustomResponse.r1<>("ok", true, result));
      } else {
        return ResponseEntity.ok(new CustomResponse.r1<>("角色未存证", true, null));
      }
    }

    // 当只有modelFile参数时的处理逻辑
    else if (modelFileOrImage != null && serial == null) {
      // 图片/.glb 文件处理
      String hashV = hashUtil.getFileHash(modelFileOrImage);  // 单张图/文件的哈希，待处理，数据库为多文件的哈希拼接
      DID did1 = didService.findByImageHash(hashV);  // 单张图/文件的哈希，待处理，数据库为多文件的哈希拼接
      DID did2 = didService.findByModelFileHash(hashV);
      DID did = (did1 != null) ? did1 : did2;

      if (did != null) {
        String txhash_saveAuth = did.getTxhash_saveAuth();
        String idCardUrl = did.getIdCardUrl();
        Map<String, Object> result = new HashMap<>();
        result.put("txhash_saveAuth", txhash_saveAuth);
        result.put("idCardUrl", idCardUrl);
        if (txhash_saveAuth != null) {
          return ResponseEntity.ok(new CustomResponse.r1<>("ok", true, result));
        } else {
          return ResponseEntity.ok(new CustomResponse.r1<>("角色未存证", true, null));
        }

      } else {
        return ResponseEntity.ok(new CustomResponse.r1<>("角色不存在", true, null));
      }
    }
    // 当两个参数都缺失或都存在时返回错误
    else {
      // 返回错误提示
      return ResponseEntity.ok(new CustomResponse.r1<>("请2选1输入编号或模型文件", true, null));
    }
  }
}
